# _*_ coding: utf-8 _*_
from odoo import models, fields, api


class PurchaseRequisition(models.Model):
    _inherit = "purchase.requisition"

    purchase_request_line_ids = fields.One2many("purchase.request.order.line",
                                                compute="_compute_purchase_request_line_ids")
    purchase_request_line_count = fields.Integer(compute="_compute_purchase_request_line_ids")

    purchase_request_order_ids = fields.One2many("purchase.request.order",
                                                 compute="_compute_purchase_request_order_ids")
    purchase_request_order_count = fields.Integer(compute="_compute_purchase_request_order_ids")

    def _compute_purchase_request_line_ids(self):
        for req in self:
            req.purchase_request_line_ids = self.env["purchase.request.order.line"].search([
                ("requisition_line_id", "in", req.line_ids.ids),
                ("state", "=", "price_comparing")
            ])
            req.purchase_request_line_count = len(req.purchase_request_line_ids)

    def _compute_purchase_request_order_ids(self):
        for req in self:
            lines = self.env["purchase.request.order.line"].search([
                ("requisition_line_id", "in", req.line_ids.ids),
                ("state", "=", "price_comparing")
            ])
            req.purchase_request_order_ids = lines.mapped("order_id")
            req.purchase_request_order_count = len(req.purchase_request_order_ids)

    @api.multi
    def action_view_purchase_request_lines(self):
        self.ensure_one()
        action = self.env.ref("tuntex_DIS022_purchase_request_order.purchase_request_order_line_action_compare_price")
        if not action:
            return True

        action_dict = action.read()[0]

        domain = [
            ("id", "in", self.purchase_request_line_ids.ids),
            ("state", "=", "price_comparing")
        ]
        action_dict["domain"] = domain
        if not self.purchase_request_line_ids:
            action_dict["context"] = None
        return action_dict

    @api.multi
    def action_view_purchase_request_orders(self):
        self.ensure_one()
        action = self.env.ref("tuntex_DIS022_purchase_request_order.purchase_request_order_action_compare_price")
        if not action:
            return True

        action_dict = action.read()[0]

        domain = [
            ("id", "in", self.purchase_request_order_ids.ids),
            ("state", "=", "price_comparing")
        ]
        action_dict["domain"] = domain
        return action_dict
